import Taro from '@tarojs/taro'
import Store from '../store/index'
import { getCurrentPageUrlWithArgs, redirectToPage } from '../utils/index'
import { IUtils } from '../interfaces/utils'
/**
 * http请求
 */
// get请求
const get = async (apiPath: IUtils['apiPath'], data) => {
  let apiRs: IUtils['apiRs'] = await apiRequest('GET', apiPath, 'application/json', data)
  return bizExect(apiRs, apiPath)
}// post表单请求
const postForm = async (apiPath: IUtils['apiPath'], data) => {
  let apiRs: IUtils['apiRs'] = await apiRequest('POST', apiPath, 'application/x-www-form-urlencoded', data)
  return bizExect(apiRs, apiPath)
}
// postJSON请求
const postJson = async (apiPath: IUtils['apiPath'], data) => {
  let apiRs: IUtils['apiRs'] = await apiRequest('POST', apiPath, 'application/json', data)
  return bizExect(apiRs, apiPath)
}
// 上传文件请求
const uploadFile = async (apiPath: IUtils['apiPath'], data) => {
  let apiRs: IUtils['apiRs'] = await apiRequest('POST', apiPath, 'multipart/form-data', data, 'uploadFile')
  return bizExect(apiRs, apiPath)
}
// 下载文件请求
const downloadFile = async (apiPath: IUtils['apiPath'], data) => {
  let apiRs: IUtils['apiRs'] = await apiRequest('GET', apiPath, 'application/json', data, 'downloadFile')
  return bizExect(apiRs, apiPath)
}
// 请求方式处理
const apiRequest = async (method: IUtils['method'], apiPath: IUtils['apiPath'], contenType: IUtils['contenType'], data, fileType?: IUtils['fileType']) => {
  if (Store.stopReq) {
    return {
      httpCode: 423,
      code: 423,
      msg: '正在登录中，放弃当前请求！',
      data: null,
      next: true
    }
  }
  const url: IUtils['url'] = getApiUrl(apiPath)
  if (fileType === 'uploadFile') {
    return await appUploadFile(method, url, contenType, data)
  } else if (fileType === 'downloadFile') {
    return await appDownloadFile(method, url, contenType, data)
  } else {
    return await appRequest(method, url, contenType, data)
  }
}
// 处理接口地址
const getApiUrl = (apiPath: IUtils['apiPath']) => {
  // @ts-ignore
  const baseUrl: IUtils['url'] = APIDOMIANS
  return `${baseUrl}/${apiPath}`
}
// 处理普通请求
const appRequest = async (method: IUtils['method'], url: IUtils['url'], contenType: IUtils['contenType'], data) => {
  const params: IUtils['requestParams'] = {
    url,
    data,
    header: getApiHeader(contenType),
    method
  }
  let wpRes: IUtils['wpRes'] = await Taro.request(params).catch(ex => {
    if (ex && ex.errMsg == 'request:fail url not in domain list') {
      return {
        statusCode: 500,
        domainerror: true
      }
    } else if (ex && ex.errMsg && ex.errMsg.indexOf('request:fail') > -1) {
      console.log(506, ex)
      return {
        statusCode: 506
      }
    } else {
      throw(ex)
    }
  })
  let res = wpRes.data
  if (res) {
    res.httpCode = wpRes.statusCode
    res.next = true
  } else {
    res = {
      httpCode: wpRes.statusCode,
      code: wpRes.statusCode,
      data: null,
      next: true,
      domainerror: wpRes.domainerror
    }
  }
  return res
}
// 处理上传请求
const appUploadFile = async (method: IUtils['method'], url: IUtils['url'], contenType: IUtils['contenType'], data) => {
  const params: IUtils['uploadParams'] = {
    url,
    filePath: data.filePath,
    name: data.name,
    formData: data.formData,
    header: getApiHeader(contenType),
    method
  }
  let wpRes = await Taro.uploadFile(params)
  let res: string = wpRes.data
  let Res: object
  if (res) {
    Res = {
      httpCode: wpRes.statusCode,
      next: true,
      data: res
    }
  } else {
    Res = {
      httpCode: wpRes.statusCode,
      code: wpRes.statusCode,
      data: null,
      next: true
    }
  }
  return Res
}
// 处理下载请求
const appDownloadFile = async (method: IUtils['method'], url: IUtils['url'], contenType: IUtils['contenType'], data) => {
  const params: IUtils['downloadParams'] = {
    url,
    header: getApiHeader(contenType),
    filePath: data.filePath,
    method
  }
  let wpRes = await Taro.downloadFile(params)
  // let res = wpRes['data']
  // if (res) {
  //   res.httpCode = wpRes.statusCode
  //   res.next = true
  // } else {
  //   res = {
  //     httpCode: wpRes.statusCode,
  //     code: wpRes.statusCode,
  //     data: null,
  //     next: true
  //   }
  // }
  let res = {
    httpCode: wpRes.statusCode,
    code: wpRes.statusCode,
    next: true
  }
  return res
}
// 处理公共请求头
const getApiHeader = (contenType: IUtils['contenType']) => {
  return {
    'Content-Type': contenType, // 数据类型
    'From': Store.model,  // 来源
    'Authorization': 'Bearer ' + Store.jwtToken // 令牌
  }
}
// 校验
const bizExect = (apiRs: IUtils['apiRs'], apiPath: IUtils['apiPath']) => {  
  apiRs.apiPath = apiPath
  if (apiRs.domainerror) {
    apiRs.next = false
    Taro.showToast({ title: '请求域名配置错误' })
  } else if (apiRs.httpCode === 423) {
    apiRs.next = false
    Taro.showToast({ title: '正在登录中，放弃当前请求！' })
  } else if (apiRs.httpCode === 403) {
    // 服务器拒绝，未登录或账号过期
    apiRs.next = false
    const returnUrl = getCurrentPageUrlWithArgs() // 保存页面
    redirectToPage(`/pages/login/index?returnUrl=${escape(returnUrl)}`)
  }
  return apiRs
}

export {
  get,
  postForm,
  postJson,
  uploadFile,
  downloadFile
}